/*
 * @Description: @login & register
 * @Author: your name
 * @Date: 2019-09-09 22:01:57
 * @LastEditTime: 2019-10-05 12:30:33
 * @LastEditors: Please set LastEditors
 */

const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const User = require('../../models/User')
const keys = require("../../config/keys")
const gravatar = require('gravatar')
const passport = require('passport')
 
 router.get('/test',(req,res)=>{
     res.json({
         msg:"login works "
     })
 }) 

router.post('/register',(req,res)=>{
    // console.log(req.body)
    // 查询数据库中是否有邮箱
    User.findOne({email:req.body.email})
        .then(data=>{
            if(data){
                return res.status(400).json('邮箱已被占用')
            }else{
                console.log(req.body)
                const avatar = gravatar.url(req.body.email,{s:'200',r:'pg',d:'mm'})
                const newUser = new User({
                    name : req.body.name,
                    email : req.body.email,
                    avatar,
                    password:req.body.password,
                    identity:req.body.identity
                })
                bcrypt.genSalt(10,function(err,salt){
                    console.log(newUser)
                    bcrypt.hash(newUser.password,salt,(err,hash)=>{
                        console.log(salt)
                        if(err) throw err;
                        newUser.password = hash
                        newUser.save()
                                .then(user=>res.json(user))
                                .catch(err =>console.log(err))
                    })
                })

            }
        })
        .catch(req=>{console.log(req)})
})


// 登录,返回token
router.post('/login',(req,res)=>{
    const email = req.body.email
    const password = req.body.password
    User.findOne({email})
        .then(user=>{
            if(!user) return res.status(404).json('用户不存在');
            // 密码匹配
            bcrypt.compare(password,user.password,function(err,isMatch){
                if(err) throw err;
                if(isMatch){
                    // jwt.sign("规则","加密名字","过期的时间","箭头函数")
                    const rule = {
                        id: user.id,
                        name: user.name,
                        avatar: user.avatar,
                        identity: user.identity,
                      };
                    jwt.sign(rule,keys.secretOrKey,{expiresIn:3600},(err,token)=>{
                        res.json({success:true,token:'Bearer '+ token})
                    })
                }else{
                    res.status(404).json('密码错误')
                }
            })
                    
        })
})



/**
 * @description: return current user 
 * @route GET api/users/current
 * @access Private
 */
router.get(
    '/current',
    passport.authenticate('jwt', { session: false }),
    (req, res) => {
      res.json(req.user);
    }
  );


 module.exports = router